package com.haozi.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haozi.reggie.common.R;
import com.haozi.reggie.dto.DishDto;
import com.haozi.reggie.entity.Category;
import com.haozi.reggie.entity.Dish;
import com.haozi.reggie.entity.DishFlavor;
import com.haozi.reggie.service.CategoryService;
import com.haozi.reggie.service.DishFlavorService;
import com.haozi.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 菜品列表
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "菜品分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示数量", required = true),
            @ApiImplicitParam(name = "name", value = "菜品名称", required = false)
    })
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //实例化分页
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //数据拷贝
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品 删除缓存
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "新增菜品")
//    @CacheEvict(value = "reggie:dish", key = "#dishDto.categoryId")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
//        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 更新菜品  删除缓存
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "更新菜品")
    @CacheEvict(value = "reggie:dish", key = "#dishDto.categoryId")
    @PutMapping
    public R<String> upload(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品修改成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> getDetail(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 停售/启售  同时删除缓存
     * @param status
     * @param ids
     * @return
     */
    @ApiOperation(value = "起售/停售")
    @CacheEvict(value = "reggie:dish",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dishLambdaUpdateWrapper.in(Dish::getId,ids);
        dishLambdaUpdateWrapper.set(Dish::getStatus,status);
        dishService.update(dishLambdaUpdateWrapper);
        return R.success("菜品更新成功");
    }

    /**
     * 删除菜品  同时删除缓存
     * @param ids
     * @return
     */
    @CacheEvict(value = "reggie:dish", allEntries = true)
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);
        return R.success("菜品删除成功");
    }

    /**
     * 获取菜品列表
     * @param categoryId
     * @return
     */
   /* @GetMapping("/list")
    public R<List<Dish>> list(Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @Cacheable(value = "reggie:dish", key = "#categoryId")
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        //查询关联表数据dish_flavor
        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //数据拷贝
            BeanUtils.copyProperties(item,dishDto);
            //获取分类名称
            Category category = categoryService.getById(categoryId);
            if(category.getName() != null) {
                dishDto.setCategoryName(category.getName());
            }
            //获取dishID
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
